package com.pt.pok.proxy.client.integration.gateway;

import com.pt.pok.GeneralProxyException;
import com.pt.pok.ProtocolConverter;
import com.pt.pok.model.PokerCommand;

import java.nio.ByteBuffer;

import static com.pt.pok.proxy.client.integration.util.net.BinaryFormatUtility.buildNetworkMessage;
import static com.pt.pok.proxy.client.integration.util.net.BinaryFormatUtility.getClassId;
import static com.pt.pok.proxy.client.integration.util.net.BinaryFormatUtility.getReadyData;
import static com.pt.pok.proxy.client.integration.util.zip.CompressionUtil.checkIfCompressionRequired;
import static com.pt.pok.proxy.client.integration.util.zip.CompressionUtil.compress;

/**
 * @author Roman.Ivanov@playtech.com
 *         <p/>
 *         TODO: javadoc
 */
public class ChannelServerSessionProxyDelegate {

    private final ProtocolConverter<byte[]> protobufConverter;
    private final ProtocolConverter<String> stringProtocolConverter;

    public ChannelServerSessionProxyDelegate(final ProtocolConverter<String> stringProtocolConverter, final ProtocolConverter<byte[]> protobufConverter) {
        this.stringProtocolConverter = stringProtocolConverter;
        this.protobufConverter = protobufConverter;
    }

    public void onBinaryMessage(final ByteBuffer networkMessage)
        throws GeneralProxyException {
        final byte[] data = getReadyData(networkMessage);
        int classId = getClassId(networkMessage);
        protobufConverter.handleCommand(classId, data);
    }

    public ByteBuffer onPokerCommand(final PokerCommand pokerCommand) {
        byte[] data = protobufConverter.convertToProtocolCommand(pokerCommand);

        boolean needCompression = checkIfCompressionRequired(data);
        if (needCompression) {
            data = compress(data);
        }

        return buildNetworkMessage(false, needCompression, pokerCommand.getClassId(), data);
    }

    public void callGatewayNetworkLayer(ByteBuffer readyToTransmitBinaryMessage) {

    }

}
